package com.app.controller;

import com.app.common.EducationTool;
import com.app.mapper.EnterpriseMapper;
import com.app.mapper.JobPublishMapper;
import com.app.mapper.MatchingSuccessfulMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.DateMaskingUtils;
import com.app.util.DateUtil;
import com.app.util.Result;
import com.app.vo.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@Controller
public class ScreenListController {
    @Autowired
    private QuestionnaireInvestigationService questionnaireInvestigationService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private JobPublishService jobPublishService;
    @Autowired
    private JobIntentionService jobIntentionService;
    @Resource
    private SkillTrainingService skillTrainingService;
    @Resource
    private VideoTrainService videoTrainService;
    @Resource
    private TrainEnrollService trainEnrollService;
    @Resource
    private StreetService streetService;
    @Resource
    private ConfigService configService;
    @Resource
    private WorkApplyService workApplyService;
    @Resource
    private BrowseNumberService browseNumberService;
    @Resource
    private CustomerService customerService;
    @Resource
    private UserService userService;
    @Resource
    private ComRecruitersService comRecruitersService;
    @Resource
    private MatchingSuccessfulMapper matchingSuccessfulMapper;

    @Autowired
    private JobPublishMapper jobPublishMapper;
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    //乡镇列表
    @GetMapping("/villageList")
    public Result<Object> villageList() {
        List<ConfigModel> list = (List<ConfigModel>) configService.villageList();
        return Result.success(findChildren(list,0));
    }

    //街道列表
    @GetMapping("/streetList")
    public Result<Object> streetList() {
        List<ConfigModel> list = (List<ConfigModel>) configService.streetList();
        return Result.success(findChildren(list,0));
    }

    private List<ConfigModel> findChildren(List<ConfigModel> modelList, Integer pid){//递归方法
        List<ConfigModel> personModelList= new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if(Objects.equals(modelList.get(i).getFatherId(), pid))
            {
                ConfigModel model = modelList.get(i);
                List<ConfigModel> modelList1 = findChildren(modelList,model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    if(modelList1!=null&&modelList1.size()>0)
                    {
                        model.setChild(modelList1);
                    }
                }
                personModelList.add(model);
            }
        }
        return personModelList;
    }
    //农村劳动力列表
    @GetMapping("/ruralList")
    public Result<Object> ruralList(Integer page, Integer limit, @RequestParam(required = false) Integer streetId) {
        Page<QuestionnaireInvestigationModel> questionnaireInvestigationPage = questionnaireInvestigationService.ruralList(page, limit, streetId);
        //对返回信息进行脱敏返回
        List<QuestionnaireInvestigationModel> questionnaireInvestigationList = questionnaireInvestigationPage.getRecords();
        if (CollectionUtils.isNotEmpty(questionnaireInvestigationList)){
            for (QuestionnaireInvestigationModel questionnaireInvestigation: questionnaireInvestigationList) {
                String realName = DateMaskingUtils.chineseName(questionnaireInvestigation.getRealName());//脱敏后的姓名
                String mobile = DateMaskingUtils.mobilePhone(questionnaireInvestigation.getMobile());//脱敏后的电话号
                String idCard = DateMaskingUtils.idCard(questionnaireInvestigation.getIdCard());//脱敏后的身份证号
                questionnaireInvestigation.setRealName(realName);
                questionnaireInvestigation.setMobile(mobile);
                questionnaireInvestigation.setIdCard(idCard);
            }
        }
        return Result.success(questionnaireInvestigationPage);
    }

    //城镇未就业列表
    @GetMapping("/unemployedList")
    public Result<Object> unemployedList(Integer page, Integer limit,Integer streetId) {
        Page<QuestionnaireInvestigationModel> questionnaireInvestigationPage = questionnaireInvestigationService.unemployedList(page, limit, streetId);
        List<QuestionnaireInvestigationModel> questionnaireInvestigationList = questionnaireInvestigationPage.getRecords();
        //对信息进行脱敏返回
        if (CollectionUtils.isNotEmpty(questionnaireInvestigationList)){
            for (QuestionnaireInvestigationModel questionnaireInvestigation : questionnaireInvestigationList) {
                String realName = DateMaskingUtils.chineseName(questionnaireInvestigation.getRealName());//脱敏后的姓名
                String mobile = DateMaskingUtils.mobilePhone(questionnaireInvestigation.getMobile());//脱敏后的电话号
                String idCard = DateMaskingUtils.idCard(questionnaireInvestigation.getIdCard());//脱敏后的身份证号
                questionnaireInvestigation.setRealName(realName);
                questionnaireInvestigation.setMobile(mobile);
                questionnaireInvestigation.setIdCard(idCard);
            }
        }
        return Result.success(questionnaireInvestigationPage);
    }

    //城镇有就业意愿列表
    @GetMapping("/intentionsList")
    public Result<Object> intentionsList(Integer page, Integer limit,Integer streetId) {
        Page<QuestionnaireInvestigationModel> questionnaireInvestigationPage = questionnaireInvestigationService.intentionsList(page, limit, streetId);
        List<QuestionnaireInvestigationModel> questionnaireInvestigationList = questionnaireInvestigationPage.getRecords();
        //对信息进行脱敏返回
        if (CollectionUtils.isNotEmpty(questionnaireInvestigationList)){
            for (QuestionnaireInvestigationModel questionnaireInvestigation : questionnaireInvestigationList) {
                String realName = DateMaskingUtils.chineseName(questionnaireInvestigation.getRealName());//脱敏后的姓名
                String mobile = DateMaskingUtils.mobilePhone(questionnaireInvestigation.getMobile());//脱敏后的电话号
                String idCard = DateMaskingUtils.idCard(questionnaireInvestigation.getIdCard());//脱敏后的身份证号
                questionnaireInvestigation.setRealName(realName);
                questionnaireInvestigation.setMobile(mobile);
                questionnaireInvestigation.setIdCard(idCard);
            }
        }
        return Result.success(questionnaireInvestigationPage);
    }

    //用人单位列表
    @GetMapping("/employersList")
    public Result<Object> employersList(Integer page, Integer limit) {
        Page<EnterpriseModel> enterpriseModelPage = enterpriseService.employersList(page, limit);
        List<EnterpriseModel> enterpriseList = enterpriseModelPage.getRecords();
        //对信息进行脱敏返回
        if (CollectionUtils.isNotEmpty(enterpriseList)){
            for (EnterpriseModel enterprise : enterpriseList) {
                //对法人名称进行脱敏
                String legalPersonName = DateMaskingUtils.chineseName(enterprise.getLegalPersonName());
                enterprise.setLegalPersonName(legalPersonName);
            }
        }
        return Result.success(enterpriseModelPage);
    }

    //在招岗位列表
    @GetMapping("/postList")
    public Result<Object> postList(Integer page, Integer limit) {
        return Result.success(jobPublishService.postList(page, limit));
    }

    //全部岗位列表
    @GetMapping("/allPostList")
    public Result<Object> allPostList(Integer page, Integer limit) {
        return Result.success(jobPublishService.allPostList(page, limit));
    }

    //求职人数列表 街道
    @GetMapping("/seekersList")
    public Result<Object> seekersList(Integer page, Integer limit, @RequestParam(required = false) Integer streetId) {
        Page<JobIntentionModel> jobIntentionModelPage = jobIntentionService.seekersList(page, limit, streetId);
        List<JobIntentionModel> jobIntentionList = jobIntentionModelPage.getRecords();
        //对信息进行脱敏
        if (CollectionUtils.isNotEmpty(jobIntentionList)){
            for (JobIntentionModel jobIntention : jobIntentionList) {
                CustomerModel customer = jobIntention.getCustomer();
                String realName = DateMaskingUtils.chineseName(customer.getRealName());//脱敏后的姓名
                customer.setRealName(realName);
                String mobile = DateMaskingUtils.mobilePhone(customer.getMobile());//脱敏后的电话号
                customer.setMobile(mobile);
            }
        }
        return Result.success(jobIntentionModelPage);
    }

    //简历投递人列表 街道
    @GetMapping("/resumeList")
    public Result<Object> resumeList(Integer page, Integer limit, Integer streetId) {
        WorkApplyVo workApplyVo = workApplyService.resumeList(page, limit, streetId);
        List<WorkApplyModel> workApplyList = workApplyVo.getList();
        //对信息进行脱敏返回
        if (CollectionUtils.isNotEmpty(workApplyList)){
            for (WorkApplyModel workApply : workApplyList) {
                EnterpriseModel enterprise = workApply.getEnterpriseModel();
                String legalPersonName = DateMaskingUtils.chineseName(enterprise.getLegalPersonName());//脱敏后的法人姓名
                String legalPersonPhone = DateMaskingUtils.mobilePhone(enterprise.getLegalPersonMobileNumber());//脱敏后的手机号
                String legalPersonId = DateMaskingUtils.idCard(enterprise.getLegalPersonId());//脱敏后的身份证号
                enterprise.setLegalPersonName(legalPersonName);
                enterprise.setLegalPersonMobileNumber(legalPersonPhone);
                enterprise.setLegalPersonId(legalPersonId);

                CustomerModel customer = workApply.getCustomer();
                String realName = DateMaskingUtils.chineseName(customer.getRealName());//脱敏后的姓名
                String mobile = DateMaskingUtils.mobilePhone(customer.getMobile());//脱敏后的手机号
                customer.setRealName(realName);
                customer.setMobile(mobile);
            }
        }
        return Result.success(workApplyVo);
    }

    //报名人数列表
    @GetMapping("/registrationList")
    public Result<Object> registrationList(Integer page, Integer limit, Integer streetId) {
        return Result.success(trainEnrollService.registrationList(page, limit, streetId));
    }

    //培训机构列表 街道
    @GetMapping("/trainList")
    public Result<Object> trainList(Integer page, Integer limit) {
        return Result.success(skillTrainingService.selectTrainList(page, limit));
    }

    //培训课程列表
    @GetMapping("/courseList")
    public Result<Object> courseList(Integer page, Integer limit) {
        return Result.success(videoTrainService.courseList(page, limit));
    }

    //工种列表
    @GetMapping("/typeWorkList")
    public Result<Object> typeWorkList(Integer page, Integer limit) {
        return null;
    }

    //所有公司列表
    @GetMapping("/enterprise")
    public Result<Object> enterprise(Integer page, Integer limit, @RequestParam(required = false) Integer streetId) {
        Page<EnterpriseModel> enterpriseModels = enterpriseService.employersList(page, limit);
        //对信息进行脱敏处理
        List<EnterpriseModel> enterpriseList = enterpriseModels.getRecords();
        if (CollectionUtils.isNotEmpty(enterpriseList)){
            for (EnterpriseModel enterprise : enterpriseList) {
                //对法人名称进行脱敏
                String legalPersonName = DateMaskingUtils.chineseName(enterprise.getLegalPersonName());
                enterprise.setLegalPersonName(legalPersonName);
            }
        }
        EnterpriseVo vo = new EnterpriseVo();
        vo.setList(enterpriseList);
        vo.setCount((int) enterpriseModels.getTotal());
        return Result.success(vo);
    }


    //访问量列表 街道
    @GetMapping("/browseNumber")
    public Result<Object> browseNumber(Integer page, Integer limit) {
        List<BrowseNumberModel> browseNumberModels = browseNumberService.selectAll(page, limit);
        for (int i = 0; i < browseNumberModels.size(); i++) {
            if (browseNumberModels.get(i).getUserId() != 0) {
                UserModel userById = userService.getUserById(browseNumberModels.get(i).getUserId());
                if (userById != null) {
                    if (userById.getCId() != null && userById.getCId() != 0) {
                        CustomerModel customerById = customerService.getCustomerById(userById.getCId());
                        if (customerById != null) {
                            browseNumberModels.get(i).setUserName(customerById.getRealName());
                            browseNumberModels.get(i).setMobile(userById.getMobile());
                            browseNumberModels.get(i).setBirthday(customerById.getBirthday());
                            if (customerById.getSex() == 1) {
                                browseNumberModels.get(i).setSex("男");
                            }
                            if (customerById.getSex() == 2) {
                                browseNumberModels.get(i).setSex("女");
                            }
                        }
                    }
                    if (userById.getRId() != null && userById.getRId() != 0) {
                        ComRecruitersModel comRecruitersById = comRecruitersService.getComRecruitersById(userById.getRId());
                        if (comRecruitersById != null) {
                            browseNumberModels.get(i).setUserName(comRecruitersById.getRealName());
                            browseNumberModels.get(i).setMobile(userById.getMobile());
                        }
                    }
                }
            }
        }
        return Result.success(browseNumberModels);
    }

    //所有用户
    @GetMapping("/customer")
    public Result<Object> customer(Integer page, Integer limit, Integer streetId) {
        List<CustomerModel> customerList = customerService.selectAll(page, limit, streetId);
        //对信息进行脱敏处理返回
        if (CollectionUtils.isNotEmpty(customerList)){
            for (CustomerModel customer : customerList) {
                //对姓名脱敏
                String realName = DateMaskingUtils.chineseName(customer.getRealName());//脱敏后的姓名
                customer.setRealName(realName);
                //对手机号脱敏
                String mobile = DateMaskingUtils.mobilePhone(customer.getMobile());//脱敏后的手机号
                customer.setMobile(mobile);
            }
        }
        int count = customerService.selectAllCount(streetId);
        CustomerListVo vo = new CustomerListVo();
        vo.setList(customerList);
        vo.setCount(count);
        return Result.success(vo);
    }

    //匹配成功数列表
    @GetMapping("/matchingSuccessfulList")
    public Result<Object> matchingSuccessfulList(Integer page, Integer limit) throws ParseException {
        page = (page - 1) * limit;
        List<MatchingSuccessfulModel> matchingSuccessfulModels = matchingSuccessfulMapper.matchingSuccessfulList(page, limit);
        if (matchingSuccessfulModels != null && !matchingSuccessfulModels.isEmpty()) {
            for (int i = 0; i < matchingSuccessfulModels.size(); i++) {
                if (matchingSuccessfulModels.get(i).getSex() == 1) {
                    matchingSuccessfulModels.get(i).setSexText("男");
                } else {
                    matchingSuccessfulModels.get(i).setSexText("女");
                }
                for (int i1 = 0; i1 < EducationTool.EDUCATION_VO_LIST.size(); i1++) {
                    if (matchingSuccessfulModels.get(i).getEduction() != null && matchingSuccessfulModels.get(i).getEduction() == EducationTool.EDUCATION_VO_LIST.get(i1).getId()) {
                        matchingSuccessfulModels.get(i).setEductionText(EducationTool.EDUCATION_VO_LIST.get(i1).getData());
                    } else {
                        matchingSuccessfulModels.get(i).setEductionText("暂无");
                    }
                }
                if (matchingSuccessfulModels.get(i).getBirthday() != null) {
                    Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(matchingSuccessfulModels.get(i).getBirthday() + "-01").getTime());
                    String date = DateUtil.yearCompare(time, CommonHelp.getNowTimestamp());
                    matchingSuccessfulModels.get(i).setAge(Integer.valueOf(date));
                } else {
                    matchingSuccessfulModels.get(i).setAge(0);
                }
            }
        }
        //对信息进行脱敏处理
        if (CollectionUtils.isNotEmpty(matchingSuccessfulModels)){
            for (MatchingSuccessfulModel matchingSuccessful : matchingSuccessfulModels) {
                //对姓名脱敏
                String realName = DateMaskingUtils.chineseName(matchingSuccessful.getRealName());//脱敏后的姓名
                matchingSuccessful.setRealName(realName);
                //对手机号脱敏
                String mobile = DateMaskingUtils.mobilePhone(matchingSuccessful.getMobile());//脱敏后的手机号
                matchingSuccessful.setMobile(mobile);
            }
        }
        Integer count = matchingSuccessfulMapper.selectCount();
        MatchingSuccessfulVo vo = new MatchingSuccessfulVo();
        vo.setList(matchingSuccessfulModels);
        vo.setCount(count);
        return Result.success(vo);
    }
    /**
     * 重点企业统计
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/getKeynoteList")
    public Result<Object> getKeynoteList(Integer page, Integer limit) {
        EnterpriseModel ent = new EnterpriseModel();
        ent.setPage((page - 1) * limit);
        ent.setLimit(limit);
        List<EnterpriseModel> enterpriseList = enterpriseMapper.getKeynotePage(ent);
        KeynoteEntListVo vo = new KeynoteEntListVo();
        List<KeynoteEntVo> list = new ArrayList<>();
        for (EnterpriseModel enterpriseModel : enterpriseList) {
            KeynoteEntVo keynoteEntVo = new KeynoteEntVo();
            keynoteEntVo.setId(enterpriseModel.getId());
            keynoteEntVo.setEntName(enterpriseModel.getEnterpriseName());
            int jobCount = jobPublishService.getJobPublishCountByComId(enterpriseModel.getId());
            keynoteEntVo.setDemandCount(jobCount);
            int jobNumber = jobPublishService.sumJobNumberByEntId(enterpriseModel.getId());
            keynoteEntVo.setDeliver(jobNumber);
            int gap = workApplyService.enterpriseWorkApplyCount(enterpriseModel.getId());
            keynoteEntVo.setGap(gap);
            if(jobNumber > 0)
            {
                int few = jobNumber - gap;
                if(few<0)
                {
                    few = 0;
                }
                double proportion = Math.rint(((double) few / (double) jobNumber)*100);
                keynoteEntVo.setProportion(proportion);
            }else{
                keynoteEntVo.setProportion(0);
            }
            list.add(keynoteEntVo);
        }
        int jobCounts = jobPublishMapper.selectJobCount();
        vo.setJobCount(jobCounts);
        vo.setList(list);
        vo.setCount(enterpriseMapper.getKeynoteCount());
        return Result.success(vo);
    }
}
